<template>
  <div class="user-info-container">
    <div class="page-header">
      <h1 class="page-title">个人中心</h1>
      <p class="page-subtitle">管理您的个人信息</p>

      <div class="content-wrapper">
        <!-- 左侧用户信息卡片 -->
        <div class="user-card">
          <div class="user-avatar-section">
            <a-avatar :src="userInfo.avatar" :size="120" class="user-avatar">
              {{ userInfo.username?.charAt(0)?.toUpperCase() }}
            </a-avatar>
            <div class="user-basic-info">
              <h2 class="user-name">{{ userInfo.username || '未设置用户名' }}</h2>
              <p class="user-role">
                <a-tag :color="userInfo.role === 'admin' ? 'red' : 'blue'">
                  {{ userInfo.role === 'admin' ? '管理员' : '普通用户' }}
                </a-tag>
              </p>
            </div>
          </div>

          <div class="user-stats">
            <div class="stat-item">
              <div class="stat-number">{{ userInfo.id || '-' }}</div>
              <div class="stat-label">用户ID</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ formatDate(userInfo.createTime) }}</div>
              <div class="stat-label">注册时间</div>
            </div>
          </div>
        </div>

        <!-- 右侧编辑表单 -->
        <div class="edit-form-card">
          <div class="form-header">
            <h3 class="form-title">编辑个人信息</h3>
            <p class="form-subtitle">您可以修改以下信息</p>
          </div>

          <a-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            layout="vertical"
            @finish="handleSubmit"
          >
            <a-form-item label="用户名" name="username">
              <a-input v-model:value="formData.username" placeholder="请输入用户名" size="large" />
            </a-form-item>

            <a-form-item label="头像URL" name="avatar">
              <a-input
                v-model:value="formData.avatar"
                placeholder="请输入头像URL地址"
                size="large"
              />
              <div class="avatar-preview" v-if="formData.avatar">
                <a-avatar :src="formData.avatar" :size="60">
                  {{ formData.username?.charAt(0)?.toUpperCase() }}
                </a-avatar>
                <span class="preview-text">预览</span>
              </div>
            </a-form-item>

            <a-form-item label="个人简介" name="profile">
              <a-textarea
                v-model:value="formData.profile"
                placeholder="请输入个人简介"
                :rows="4"
                :maxlength="200"
                show-count
              />
            </a-form-item>

            <a-form-item>
              <a-space>
                <a-button type="primary" html-type="submit" size="large" :loading="loading">
                  <template #icon>
                    <SaveOutlined />
                  </template>
                  保存修改
                </a-button>
                <a-button size="large" @click="handleReset">
                  <template #icon>
                    <ReloadOutlined />
                  </template>
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { ReloadOutlined, SaveOutlined } from '@ant-design/icons-vue'
import { getLoginUser, updateMyUser } from '@/api/userController'
import { useLoginUserStore } from '@/stores/loginUser'

// 定义组件名称
defineOptions({
  name: 'UserInfo',
})

const loginUserStore = useLoginUserStore()

// 响应式数据
const loading = ref(false)
const userInfo = ref<API.LoginUserVO>({})

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive<API.UserUpdateMyRequest>({
  username: '',
  avatar: '',
  profile: '',
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  avatar: [{ type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }],
  profile: [{ max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }],
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getLoginUser()
    if (res.code === 0 && res.data) {
      userInfo.value = res.data
      // 同步到表单数据
      Object.assign(formData, {
        username: res.data.username || '',
        avatar: res.data.avatar || '',
        profile: res.data.profile || '',
      })
    }
  } catch {
    message.error('获取用户信息失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    const res = await updateMyUser(formData)
    if (res.code === 0) {
      message.success('个人信息更新成功')
      // 更新全局状态
      await loginUserStore.fetchLoginUser()
      // 重新获取用户信息
      await fetchUserInfo()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  Object.assign(formData, {
    username: userInfo.value.username || '',
    avatar: userInfo.value.avatar || '',
    profile: userInfo.value.profile || '',
  })
  formRef.value?.resetFields()
  message.info('表单已重置')
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.content-wrapper {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 24px;
}

.user-card {
  padding: 24px;
  height: fit-content;
}

.user-avatar-section {
  text-align: center;
  margin-bottom: 24px;
}

.user-avatar {
  margin-bottom: 16px;
  border: 4px solid #f0f0f0;
}

.user-basic-info {
  text-align: center;
}

.user-name {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.user-role {
  margin: 8px 0;
}

.user-account {
  font-size: 14px;
  color: #666;
  margin: 8px 0 0 0;
}

.user-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.edit-form-card {
  padding: 24px;
}

.form-header {
  margin-bottom: 24px;
}

.form-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.form-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.avatar-preview {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.preview-text {
  font-size: 12px;
  color: #666;
}

.other-actions {
  margin-top: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .content-wrapper {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .user-info-container {
    padding: 16px;
  }

  .page-header,
  .user-card,
  .edit-form-card {
    padding: 16px;
  }
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-input-affix-wrapper) {
  border-radius: 6px;
}

:deep(.ant-btn) {
  border-radius: 6px;
}
</style>
